<script setup>

import {loginUser} from '@/api/user'
import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import router from '../../router';

//表单对象
const loginForm = ref({
    username:'',
    password:''
})



//关联表单
const loginFormRef = ref(null)
//校验规则
const loginRules =ref({
  username: [
    { required: true, message: '账号不能为空！', trigger: 'blur' },
    { min: 3, max: 25, message: '账号长度请在3-25位之间！', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { min: 3, max: 25, message: '密码长度请在3-25位之间！', trigger: 'blur' },
  ]
})

//登录方法
const submitForm = async()=>{
    if (!loginFormRef.value) return
    await loginFormRef.value.validate(async (valid, fields) => {
        if (valid) {
        let result = await loginUser(loginForm.value)
        if(result.code==1){
            //将登录成功的数据放到localStorage
            localStorage.setItem('userInfo',JSON.stringify(result.data))
            //跳转至主页
            ElMessage.success('登录成功')
            router.push('/')
        }else{
            ElMessage.error('登录失败')
        }
        
        } else {
        console.log('校验失败!', fields)
        }
    })
    
}


</script>

<template>
    <el-form 
        :model="loginForm" 
        :rules="loginRules"
        ref="loginFormRef"
        label-width="auto" 
        style="max-width: 600px">
            <el-form-item label="账号" prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">登录</el-button>
            </el-form-item>
    </el-form>
</template>

<style scoped>
</style>